import '../models/check_in_record.dart';
import '../services/web_database_service.dart';

class CheckInRecordRepository {
  final WebDatabaseService _dbService = WebDatabaseService();
  static const String _tableName = WebDatabaseService.checkInRecordsTable;

  /// 添加签到记录
  Future<int> addCheckInRecord(CheckInRecord record) async {
    final data = record.toMap();
    data.remove('id'); // 移除id，让数据库自动生成
    return await _dbService.insert(_tableName, data);
  }

  /// 获取所有签到记录
  Future<List<CheckInRecord>> getAllCheckInRecords() async {
    final results = await _dbService.getAll(_tableName);
    return results.map((data) => CheckInRecord.fromMap(data)).toList();
  }

  /// 根据ID获取签到记录
  Future<CheckInRecord?> getCheckInRecordById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? CheckInRecord.fromMap(result) : null;
  }

  /// 根据日期获取签到记录
  Future<CheckInRecord?> getCheckInRecordByDate(DateTime date) async {
    final dateTimestamp = DateTime(date.year, date.month, date.day).millisecondsSinceEpoch;
    final results = await _dbService.getByIndex(_tableName, 'date', dateTimestamp);
    
    if (results.isNotEmpty) {
      return CheckInRecord.fromMap(results.first);
    }
    return null;
  }

  /// 检查今日是否已签到
  Future<bool> isTodayCheckedIn() async {
    final today = DateTime.now();
    final record = await getCheckInRecordByDate(today);
    return record != null;
  }

  /// 获取今日签到记录
  Future<CheckInRecord?> getTodayCheckInRecord() async {
    final today = DateTime.now();
    return await getCheckInRecordByDate(today);
  }

  /// 获取最近的签到记录
  Future<List<CheckInRecord>> getRecentCheckInRecords(int count) async {
    final allRecords = await getAllCheckInRecords();
    allRecords.sort((a, b) => b.date.compareTo(a.date));
    return allRecords.take(count).toList();
  }

  /// 获取指定日期范围的签到记录
  Future<List<CheckInRecord>> getCheckInRecordsByDateRange(
    DateTime startDate,
    DateTime endDate,
  ) async {
    final allRecords = await getAllCheckInRecords();
    final startTimestamp = DateTime(startDate.year, startDate.month, startDate.day).millisecondsSinceEpoch;
    final endTimestamp = DateTime(endDate.year, endDate.month, endDate.day, 23, 59, 59).millisecondsSinceEpoch;
    
    return allRecords.where((record) => 
      record.date >= startTimestamp && record.date <= endTimestamp
    ).toList();
  }

  /// 获取本周签到记录
  Future<List<CheckInRecord>> getThisWeekCheckInRecords() async {
    final now = DateTime.now();
    final startOfWeek = now.subtract(Duration(days: now.weekday - 1));
    final startOfWeekDay = DateTime(startOfWeek.year, startOfWeek.month, startOfWeek.day);
    
    return await getCheckInRecordsByDateRange(startOfWeekDay, now);
  }

  /// 获取本月签到记录
  Future<List<CheckInRecord>> getThisMonthCheckInRecords() async {
    final now = DateTime.now();
    final startOfMonth = DateTime(now.year, now.month, 1);
    
    return await getCheckInRecordsByDateRange(startOfMonth, now);
  }

  /// 获取连续签到天数
  Future<int> getConsecutiveCheckInDays() async {
    final allRecords = await getAllCheckInRecords();
    if (allRecords.isEmpty) return 0;
    
    // 按日期排序（最新的在前）
    allRecords.sort((a, b) => b.date.compareTo(a.date));
    
    int consecutiveDays = 0;
    DateTime? lastDate;
    
    for (final record in allRecords) {
      final recordDate = DateTime.fromMillisecondsSinceEpoch(record.date);
      final recordDateOnly = DateTime(recordDate.year, recordDate.month, recordDate.day);
      
      if (lastDate == null) {
        // 第一条记录
        final today = DateTime.now();
        final todayOnly = DateTime(today.year, today.month, today.day);
        final yesterday = todayOnly.subtract(const Duration(days: 1));
        
        if (recordDateOnly == todayOnly || recordDateOnly == yesterday) {
          consecutiveDays = 1;
          lastDate = recordDateOnly;
        } else {
          break; // 不是连续的
        }
      } else {
        final expectedDate = lastDate.subtract(const Duration(days: 1));
        if (recordDateOnly == expectedDate) {
          consecutiveDays++;
          lastDate = recordDateOnly;
        } else {
          break; // 不是连续的
        }
      }
    }
    
    return consecutiveDays;
  }

  /// 更新签到记录
  Future<void> updateCheckInRecord(CheckInRecord record) async {
    await _dbService.update(_tableName, record.toMap());
  }

  /// 删除签到记录
  Future<void> deleteCheckInRecord(int id) async {
    await _dbService.delete(_tableName, id);
  }

  /// 获取签到记录总数
  Future<int> getCheckInRecordCount() async {
    return await _dbService.count(_tableName);
  }

  /// 获取签到统计
  Future<Map<String, dynamic>> getCheckInStats() async {
    final allRecords = await getAllCheckInRecords();
    final totalDays = allRecords.length;
    final consecutiveDays = await getConsecutiveCheckInDays();
    
    final totalStudyTime = allRecords.fold<int>(0, (sum, record) => sum + record.studyTime);
    final totalWordsLearned = allRecords.fold<int>(0, (sum, record) => sum + record.wordsLearned);
    final totalQuestionsAnswered = allRecords.fold<int>(0, (sum, record) => sum + record.questionsAnswered);
    
    final averageStudyTime = totalDays > 0 ? (totalStudyTime / totalDays) : 0.0;
    final averageWordsLearned = totalDays > 0 ? (totalWordsLearned / totalDays) : 0.0;
    final averageQuestionsAnswered = totalDays > 0 ? (totalQuestionsAnswered / totalDays) : 0.0;
    
    return {
      'totalDays': totalDays,
      'consecutiveDays': consecutiveDays,
      'totalStudyTime': totalStudyTime,
      'totalWordsLearned': totalWordsLearned,
      'totalQuestionsAnswered': totalQuestionsAnswered,
      'averageStudyTime': averageStudyTime,
      'averageWordsLearned': averageWordsLearned,
      'averageQuestionsAnswered': averageQuestionsAnswered,
    };
  }

  /// 获取本月签到统计
  Future<Map<String, dynamic>> getThisMonthCheckInStats() async {
    final monthRecords = await getThisMonthCheckInRecords();
    final totalDays = monthRecords.length;
    
    final totalStudyTime = monthRecords.fold<int>(0, (sum, record) => sum + record.studyTime);
    final totalWordsLearned = monthRecords.fold<int>(0, (sum, record) => sum + record.wordsLearned);
    final totalQuestionsAnswered = monthRecords.fold<int>(0, (sum, record) => sum + record.questionsAnswered);
    
    return {
      'totalDays': totalDays,
      'totalStudyTime': totalStudyTime,
      'totalWordsLearned': totalWordsLearned,
      'totalQuestionsAnswered': totalQuestionsAnswered,
    };
  }

  /// 获取签到日历数据（用于显示签到日历）
  Future<Map<String, bool>> getCheckInCalendar(int year, int month) async {
    final startDate = DateTime(year, month, 1);
    final endDate = DateTime(year, month + 1, 0); // 本月最后一天
    
    final records = await getCheckInRecordsByDateRange(startDate, endDate);
    final calendar = <String, bool>{};
    
    for (final record in records) {
      final date = DateTime.fromMillisecondsSinceEpoch(record.date);
      final dateKey = '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
      calendar[dateKey] = true;
    }
    
    return calendar;
  }

  /// 清空所有签到记录
  Future<void> clearAllCheckInRecords() async {
    await _dbService.clearTable(_tableName);
  }
}